package eu.gline.km.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.logging.ConsoleHandler;
import java.util.logging.Level;
import java.util.logging.Logger;

public class KmServer {
	
	private int defaultPort = 9900;
	private boolean loop = true;
	private ArrayList<KmClient> clients;
	
	private Logger logger;
	private ConsoleHandler ch;
	
	public KmServer(int port) {
		init(port);
	}
	
	public KmServer() {
		init(defaultPort);
	}
	
	private void init(int port) {
		inst();
		initLogger();
		createServer(port);
	}
	
	private void inst() {
		clients = new ArrayList<KmClient>();
	}
	
	private void initLogger() {
		logger = Logger.getLogger("IrcLog");
		ch = new ConsoleHandler();
		ch.setLevel(Level.ALL);
		logger.setLevel(Level.ALL);
		logger.addHandler(ch);
		
		logger.log(Level.FINEST, "Logger started");
	}
	
	private void createServer(int port) {
		try {
			ServerSocket ss = new ServerSocket(port);
			logger.log(Level.FINE, "ServerSocket started");
			
			Socket socket = null;
			while (loop) {
				socket = ss.accept();
				addClient(socket);
			}
			
		} catch (IOException e) {
			logger.log(Level.SEVERE, "IOException, ServerSocket died");
			e.printStackTrace();
		}
		
	}
	
	public void addClient(Socket s) {
		logger.log(Level.FINE, "New client detected - Hostname: " + s.getInetAddress().getHostName());
		KmClient kmc = new KmClient(this, s);
		kmc.start();
		clients.add(kmc);
	}
	
	public boolean removeClient(KmClient kmc) {
		logger.log(Level.FINE, "Removing client: " + kmc.getSocket().getInetAddress().getHostName());
		return clients.remove(kmc);
	}
	
	public Logger getLogger() {
		return logger;
	}

}
